package com.leal.kafka

import com.leal.util.SparkUtil
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkContext
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe

/**
 * @Classname bigdata
 * @Description KafkaCustomer
 * @Date 2023/2/28 18:51
 * @Created by leal
 */
object KafkaCustomer {
  def main(args: Array[String]): Unit = {

    val spark: SparkSession = SparkUtil.initSpark( enableHive = true)
    val sc: SparkContext = spark.sparkContext
    val checkpointDir = "."
    val ssc: StreamingContext = new StreamingContext(sc, Seconds(5))
    ssc.checkpoint(checkpointDir)
    val topics: Array[String] = Array("quickstart-events")

    // Create a local StreamingContext with two working thread and batch interval of 1 second.
    // The master requires 2 cores to prevent a starvation scenario.
    val kafkaParams: Map[String, Object] = Map[String, Object](
      "bootstrap.servers" -> "127.0.0.1:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "test-group-id",
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    val stream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )
    val resultDStream: DStream[(String, String)] = stream.map((x: ConsumerRecord[String, String]) => (x.key(), x.value()))
    resultDStream.print()
    ssc.start()
    ssc.awaitTermination()
  }
}
